package com.houdoudou.customer.me;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.bean.Customer;
import com.houdoudou.customer.R;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.TransPasswordUtil;
import com.houdoudou.customer.common.UniversalHttpPost;

import android.app.Activity;
import android.app.Instrumentation;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class SetPaySecretAct extends Activity{
   
	ImageButton back;
	Button confirm,getverify;
	EditText tel,secret1,secret2,verify;
	ProgressBar progres;
	TextView  result;
	View.OnClickListener myOnClickListener;
	private static final String AFFAIRCREATEVERIFY="createTelnumVerify";
	private static final String AFFAIRUPDATEPAYSECRET="updatePaySecret";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_paysecret);
		
        init_listener();
		
		confirm=(Button) findViewById(R.id.btn_confirm_act_paysecret);
		tel= (EditText) findViewById(R.id.et_tel_act_paysecret);
		secret1=(EditText) findViewById(R.id.et_secret1_act_paysecret);
		secret2=(EditText) findViewById(R.id.et_secret2_act_paysecret);
		back=(ImageButton) findViewById(R.id.back_act_paysecret);
		progres= (ProgressBar) findViewById(R.id.prgs_act_paysecret);
		result= (TextView) findViewById(R.id.tv_result_act_paysecret);
		verify= (EditText) findViewById(R.id.et_verifycode_act_paysecret);
		getverify=(Button) findViewById(R.id.btn_getverifycode_act_paysecret);
		
		progres.setVisibility(View.GONE);
		result.setVisibility(View.GONE);
		
		back.setOnClickListener(myOnClickListener);
		getverify.setOnClickListener(myOnClickListener);
		confirm.setOnClickListener(myOnClickListener);
		tel.setText(Constant.customerJO.getString(Customer.TELNUM));
	}
	private void init_listener(){
		myOnClickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(v==back){
					new Thread () { 
						public void run () { 
						try { 									
						Instrumentation inst= new Instrumentation(); 
						inst.sendKeyDownUpSync(KeyEvent. KEYCODE_BACK); 
						} catch(Exception e) { 
						e.printStackTrace(); 
						         } 
						  } 
						}.start();
				 }
				if(v==getverify){
					    getverify.setClickable(false);
					    progres.setVisibility(View.VISIBLE);					
						result.setVisibility(View.GONE);
						String[] params= new String[5];
			            params[0]=Constant.BaseUrl+Constant.CustomerUrl;
		                params[1]=AFFAIRCREATEVERIFY; //PostCod
		                JSONObject jsonData=new JSONObject();								
			            jsonData.put("telnum", tel.getText().toString());		               
			            params[2]=jsonData.toString();
		             new HttpPostTask().execute(params);
				}
				if(v==confirm){
					boolean checkinput=true;
					
					if(!secret1.getText().toString().equals(secret2.getText().toString())){
						checkinput=false;
						Toast.makeText(SetPaySecretAct.this, "两次密码输入不一致",Toast.LENGTH_SHORT ).show();}
					if(verify.getText().toString().length()!=4){
						checkinput=false;
						Toast.makeText(SetPaySecretAct.this, "验证码位数不对",Toast.LENGTH_SHORT ).show();}
					if(secret1.getText().toString().length()!=6){
						checkinput=false;
						Toast.makeText(SetPaySecretAct.this, "密码长度6位",Toast.LENGTH_SHORT ).show();}
					if(checkinput){
					  progres.setVisibility(View.VISIBLE);					
						result.setVisibility(View.GONE);
						 getverify.setClickable(false);
						 confirm.setClickable(false);
						String[] params= new String[5];
			            params[0]=Constant.BaseUrl+Constant.CustomerUrl;
		                params[1]=AFFAIRUPDATEPAYSECRET; //PostCod
		                JSONObject jsonData=new JSONObject();		                
						 JSONObject jsonVerify= new JSONObject();
						 jsonVerify.put("telnum",  tel.getText().toString());
						 jsonVerify.put("code", verify.getText().toString());
						 jsonData.put("verify", jsonVerify);
						 
						 JSONObject jsonCustomer= JSONObject.fromObject(Constant.customerJO);
						 try {
							String cipherText= TransPasswordUtil.encrypt(secret1.getText().toString());
							 jsonCustomer.put(Customer.PAYSECRET, cipherText);
						} catch (Exception e) {e.printStackTrace();}			               			              
			               jsonData.put("customer", jsonCustomer);  
			               
			                params[2]=jsonData.toString();
		             new HttpPostTask().execute(params);
					}
				}
				
				
			}
		};
	}
	
	
private  class HttpPostTask extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			 Map<String,Object> map = new HashMap<String ,Object>();		
		  map =	UniversalHttpPost.doPost(params);	             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
		
			 progres.setVisibility(View.GONE);	
			 getverify.setClickable(true);
			
			 System.out.println("-----------onPostExecute()--------------");
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				 result.setVisibility(View.VISIBLE);
				  result.setText("无法连接服务器,");
		      return;
			}
			//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
				Boolean success=false;
				String errorInfo="";
				String affair="";
				JSONObject json = null;
				try{
			     json= JSONObject.fromObject(PostResult);
				 success=json.getBoolean("success");
				 errorInfo=json.getString("errorInfo");	
				 affair=json.getString("affair");	
				}catch(JSONException e){
					 result.setVisibility(View.VISIBLE);
					  result.setText("数据解析错误");
					  return;
				}
										   												      		       
		       if(!success){  
		    	          result.setVisibility(View.VISIBLE);
          	             result.setText(errorInfo); return; }
		       if(affair.equals(AFFAIRCREATEVERIFY)){
		    	  	getverify.setText("验证码已发送");}
		       if(affair.equals(AFFAIRUPDATEPAYSECRET)){		    	  
		    	  	Toast.makeText(SetPaySecretAct.this, "设置成功，即将跳转", Toast.LENGTH_SHORT).show();
		    	  	Constant.customerJO.put(Customer.PAYSECRET, "不为空");
		    	  	SetPaySecretAct.this.finish();
		       }
		             		
		  		
			
		} //onPostExecute
 } //AsyncTask
	
}
